#import('dart:io');
#import('dart:json');
var IP='127.0.0.1';
var PORT=8080;

Map<String, Connection> connections;

class Connection {
  final int token;
  final WebSocketConnection conn;
  
  Connection(token, conn) : token = token, conn = conn {
    conn.onMessage = (message) {
      var jdata = JSON.parse(message);
      if (jdata["cmd"] == "updateBall") { 
        print("broadcasting $message");
        connections.forEach((k,v) {
          v.conn.send(message);
        });
      }
    };
    
    conn.onClosed = (int status, String reason) {
      print('closed with $status for $reason');
      connections.remove(token.toString());
    };
          
    conn.onError = (e) {
      print('Error was $e');
      connections.remove(token.toString());
    };
  }
  
  String toString() {
    return "$token";
  }
}

void main() {
  int token = 0;
  connections = new Map();
  
  HttpServer server = new HttpServer();
  WebSocketHandler wsHandler = new WebSocketHandler();
  server.addRequestHandler((req) => req.path == "/ws", wsHandler.onRequest);
  
  server.addRequestHandler((req) => req.path == "/", (HttpRequest req, HttpResponse res) {
    File file = new File("./sample_client.html"); 
    file.openInputStream().pipe(res.outputStream); 
  });
  server.addRequestHandler((req) => req.path == "/sample_client.dart", (HttpRequest req, HttpResponse res) {
    File file = new File("./sample_client.dart"); 
    file.openInputStream().pipe(res.outputStream); 
  });
  
  
  wsHandler.onOpen = (WebSocketConnection conn) {
    token+=1;
    var c = new Connection(token, conn);
    print("adding connection token = ${token}");
    connections[token.toString()] = c;
    conn.send(JSON.stringify({"cmd": "token", "arg": token.toString() }));
  };
  
  print('listing on http://$IP:$PORT');
  server.listen(IP, PORT);
}